<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="springmvc," />










<meta name="description" content="SpringMVC一、简介SpringMVC是基于ServletAPI构建的原始Web框架 SpringMVC在控制层 作用：接收前端参数、响应前端数据   SpringMVC组件：  DispatcherServlet: SpringMVC提供的，所有请求都经过它的处理和分发 HandlerMapping: 它内部缓存handler（controller方法）和Handler访问路径，被Disp">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringMVC">
<meta property="og:url" content="https://gitee.com/htt-sub/htt-sub/2023/10/29/SpringMVC/index.html">
<meta property="og:site_name" content="黄宏涛">
<meta property="og:description" content="SpringMVC一、简介SpringMVC是基于ServletAPI构建的原始Web框架 SpringMVC在控制层 作用：接收前端参数、响应前端数据   SpringMVC组件：  DispatcherServlet: SpringMVC提供的，所有请求都经过它的处理和分发 HandlerMapping: 它内部缓存handler（controller方法）和Handler访问路径，被Disp">
<meta property="og:locale">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231029182010178.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231030103606693.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231029214810811.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231029215217962.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231030091815555.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231030092008587.png">
<meta property="article:published_time" content="2023-10-28T16:00:00.000Z">
<meta property="article:modified_time" content="2023-10-30T04:57:52.402Z">
<meta property="article:author" content="黄宏涛">
<meta property="article:tag" content="springmvc">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231029182010178.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"post","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/htt-sub/htt-sub/2023/10/29/SpringMVC/"/>





  <title>SpringMVC | 黄宏涛</title>
  








<meta name="generator" content="Hexo 6.3.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-post page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">黄宏涛</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/htt-sub/htt-sub/2023/10/29/SpringMVC/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="黄宏涛">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SpringMVC</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2023-10-29T00:00:00+08:00">
                2023-10-29
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/SSM/" itemprop="url" rel="index">
                    <span itemprop="name">SSM</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="SpringMVC"><a href="#SpringMVC" class="headerlink" title="SpringMVC"></a>SpringMVC</h1><h2 id="一、简介"><a href="#一、简介" class="headerlink" title="一、简介"></a>一、简介</h2><p>SpringMVC是基于ServletAPI构建的原始Web框架</p>
<p><strong>SpringMVC在控制层</strong></p>
<p><strong>作用：</strong>接收前端参数、响应前端数据</p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231029182010178.png" alt="image-20231029182010178"></p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231030103606693.png" alt="image-20231030103606693"></p>
<p><strong>SpringMVC组件：</strong></p>
<ul>
<li><strong>DispatcherServlet:</strong> SpringMVC提供的，所有请求都经过它的处理和分发</li>
<li><strong>HandlerMapping:</strong> 它内部缓存handler（controller方法）和Handler访问路径，被DispatcherServlet调用，用于查找路径对应的handler（秘书）</li>
<li><strong>HandlerAdapter：</strong> 处理请求参数和处理响应数据，每次DispatcherServlet通过handlerAdapter间接调用handler（经理）</li>
<li><strong>handler：</strong> &#x3D;&#x3D;handler处理器&#x3D;&#x3D;，他是Controller类内部方法的简称，由我们定义，用于接受参数、向后调用业务，返回响应结果（工人）</li>
<li><strong>viewResoler:</strong> 简化模版视图页面查找的。在前后端分离项目，后端只返回JSON数据，不返回页面，不需要视图解析器。</li>
</ul>
<h3 id="快速入门"><a href="#快速入门" class="headerlink" title="快速入门"></a>快速入门</h3><blockquote>
<p>依赖</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">          &lt;groupId&gt;jakarta.platform&lt;/groupId&gt;</span><br><span class="line">          &lt;artifactId&gt;jakarta.jakartaee-web-api&lt;/artifactId&gt;</span><br><span class="line">          &lt;version&gt;<span class="number">9.1</span><span class="number">.0</span>&lt;/version&gt;</span><br><span class="line">          &lt;scope&gt;provided&lt;/scope&gt;</span><br><span class="line">      &lt;/dependency&gt;</span><br><span class="line">      &lt;dependency&gt;</span><br><span class="line">          &lt;groupId&gt;org.springframework&lt;/groupId&gt;</span><br><span class="line">          &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;</span><br><span class="line">          &lt;version&gt;<span class="number">6.0</span><span class="number">.6</span>&lt;/version&gt;</span><br><span class="line">      &lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>配置类</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan(basePackages = &quot;com&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MvcConfig</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1. controller配置IOC容器</span></span><br><span class="line"><span class="comment">     * 2. handleMapping、handlerAdapter加入到IOC容器</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> RequestMappingHandlerMapping <span class="title function_">handlerMapping</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">RequestMappingHandlerMapping</span>();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> RequestMappingHandlerAdapter <span class="title function_">handlerAdapter</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">RequestMappingHandlerAdapter</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>DispatcherServlet初始化</p>
</blockquote>
<p>本质是调用WebApplicationInitializer接口的onStratup方法，项目一启动就调用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 可以被Web项目加载，初始化IOC容器，设置DispatcherServlet的地址</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SpringMvcInit</span> <span class="keyword">extends</span> <span class="title class_">AbstractAnnotationConfigDispatcherServletInitializer</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// service层和mapper层的IOC容器配置</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Class&lt;?&gt;[] getRootConfigClasses() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Class</span>[<span class="number">0</span>];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//设置我们项目对应的配置类</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Class&lt;?&gt;[] getServletConfigClasses() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Class</span>[]&#123;MvcConfig.class&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//配置DispaterServlet拦截的地址</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> String[] getServletMappings() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">String</span>[]&#123;<span class="string">&quot;/&quot;</span>&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>Controller类</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;hello&quot;)</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">hello</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;你好&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="二、SpringMvc接收数据"><a href="#二、SpringMvc接收数据" class="headerlink" title="二、SpringMvc接收数据"></a>二、SpringMvc接收数据</h2><blockquote>
<p>@RequestMapping</p>
</blockquote>
<p>@RequestMapping：<strong>将请求的URL地址和处理请求的方式（handler方法）关联起来</strong>，建立映射关系。</p>
<p>@GetMapping：只接受get请求。</p>
<h3 id="接收参数"><a href="#接收参数" class="headerlink" title="接收参数"></a>接收参数</h3><p>GET请求采用param类型的参数，POST请求采用JSON类型的参数传递</p>
<ol>
<li><p><strong>直接接值</strong></p>
<p>只要参数名和传递参数名相同，即可自动接收</p>
</li>
<li><p><strong>@RequestParam注解</strong></p>
<p>讲过请求参数绑定到控制器中方法参数</p>
<p><strong>参数名和形参名一致，可以只写@RequestParam</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestParam(value = &quot;name&quot;,required = false,defaultValue = &quot;黄&quot;)</span> String name</span><br><span class="line">可以设置是否这个参数是否必须，也可以设置默认值</span><br><span class="line">    </span><br><span class="line"><span class="meta">@RequestParam</span> List&lt;User&gt; list</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>@PathVariable</strong></p>
</li>
</ol>
<p>​		在URL路径中传递参数方式</p>
<pre><code>    <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;hello/&#123;id&#125;&quot;)</span></span><br><span class="line">   <span class="keyword">public</span> String <span class="title function_">hello</span><span class="params">(<span class="meta">@PathVariable(&quot;id&quot;)</span> String id)</span></span><br></pre></td></tr></table></figure>
</code></pre>
<ol start="4">
<li><p><strong>JSON参数接收</strong></p>
<pre><code><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 出现415异常：</span></span><br><span class="line"><span class="comment">     * Java原生不支持JSON</span></span><br><span class="line"><span class="comment">     * 解决：1，导入JSON处理的依赖 </span></span><br><span class="line"><span class="comment">     		2，handlerAdapter配置JSON转化器(添加<span class="doctag">@EnableWebMvc</span>注解)</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;hello&quot;)</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">hello</span><span class="params">(<span class="meta">@RequestBody</span> User user)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> user.toString();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ol>
<p>JSON依赖</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">          &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;</span><br><span class="line">          &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;</span><br><span class="line">          &lt;version&gt;<span class="number">2.15</span><span class="number">.1</span>&lt;/version&gt;</span><br><span class="line">      &lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EnableWebMvc</span> <span class="comment">//相当于给handlerAdapter配置JSON转化器</span></span><br></pre></td></tr></table></figure>

<ol start="5">
<li><strong>@EnableWebMvc注解</strong></li>
</ol>
<p>相当于XML配置中，使用<a href="mvc:annotation-driven">mvc:annotation-driven</a></p>
<ol start="6">
<li>接收Cookie数据</li>
</ol>
<p>将HTTP Cookie的值绑定到控制器中的方法参数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CookieValue(&quot;cookName&quot;)</span> String cookie</span><br></pre></td></tr></table></figure>

<ol start="7">
<li>接收请求头数据</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestHeader(&quot;Host&quot;)</span> String host</span><br></pre></td></tr></table></figure>

<h2 id="三、SpringMvc响应数据"><a href="#三、SpringMvc响应数据" class="headerlink" title="三、SpringMvc响应数据"></a>三、SpringMvc响应数据</h2><blockquote>
<p>转发和重定向</p>
</blockquote>
<p>转发：forward</p>
<p>重定向：redirect</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">redirect:<span class="string">&quot;/hello&quot;</span></span><br><span class="line">forward:http:<span class="comment">//www.baidu.com</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>返回JSON数据</strong></p>
</blockquote>
<ol>
<li>开启&#x3D;&#x3D;<strong>@EnableWebMvc注解</strong>&#x3D;&#x3D;</li>
<li><strong>@ResponseBody</strong></li>
<li><strong>@RestController</strong>&#x3D;@Controller+@ResponseBody</li>
</ol>
<blockquote>
<p>静态资源处理（<strong>非前后端分离项目配置</strong>）</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan(basePackages = &quot;com&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MvcConfig</span> <span class="keyword">implements</span> <span class="title class_">WebMvcConfigurer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configureViewResolvers</span><span class="params">(ViewResolverRegistry registry)</span> &#123;</span><br><span class="line">        registry.jsp(<span class="string">&quot;/WEB-INF/vies&quot;</span>,<span class="string">&quot;.jsp&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//开启静态资源查找</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configureDefaultServletHandling</span><span class="params">(DefaultServletHandlerConfigurer configurer)</span> &#123;</span><br><span class="line">        configurer.enable();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="四、RestFul风格"><a href="#四、RestFul风格" class="headerlink" title="四、RestFul风格"></a>四、RestFul风格</h2><p>设计网络程序和服务之间的通信，HTTP协议最标准的使用方案。</p>
<blockquote>
<p>风格特点</p>
</blockquote>
<ol>
<li>每一个URL代表1种资源</li>
<li>客户端使用GET、POST（新建资源）、PUT（更新资源）、DELETE对服务端进行操作</li>
<li>资源表现形式是XML或JSON</li>
<li>客户端与服务端之间的交互是无状态的</li>
</ol>
<blockquote>
<p>设计规范</p>
</blockquote>
<ul>
<li>查询操作：GET</li>
<li>保存操作：POST</li>
<li>删除操作：DELETE</li>
<li>更新操作：PUT</li>
</ul>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231029214810811.png" alt="image-20231029214810811"></p>
<ul>
<li>总结：<strong>路径设计原来携带动词，全部改为名词，对应资源的唯一标识</strong></li>
</ul>
<h3 id="实战"><a href="#实战" class="headerlink" title="实战"></a>实战</h3><p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231029215217962.png" alt="image-20231029215217962"></p>
<p>为什么查询用户详情使用路径传递参数</p>
<ul>
<li>对于<strong>查询用户详情</strong>（GET &#x2F;user&#x2F;1 ）：使用<strong>路径传参</strong>是因为这是一个<strong>单一资源的查询</strong>，即查询一条用户记录</li>
<li>对于<strong>多条件的模糊查询</strong>，使用<strong>请求参数传参</strong>是因为这是一个<strong>资源的集合的查询</strong>，即查询多条用户记录。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EnableWebMvc</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//分页查询</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/user&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> List&lt;User&gt; <span class="title function_">page</span><span class="params">(<span class="meta">@RequestParam</span> <span class="type">int</span> page,<span class="meta">@RequestParam</span> <span class="type">int</span> size)</span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//用户添加</span></span><br><span class="line">    <span class="meta">@PostMapping(&quot;/user&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> User <span class="title function_">save</span><span class="params">(<span class="meta">@RequestBody</span> User user)</span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//用户详情</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/user/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> User <span class="title function_">query</span><span class="params">(<span class="meta">@PathVariable</span> Integer id)</span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//用户更新</span></span><br><span class="line">    <span class="meta">@PutMapping(&quot;/user&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(<span class="meta">@RequestBody</span> User user)</span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//用户删除</span></span><br><span class="line">    <span class="meta">@DeleteMapping(&quot;/user/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span>  <span class="title function_">delete</span><span class="params">(<span class="meta">@PathVariable</span> Integer id)</span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="五、拓展"><a href="#五、拓展" class="headerlink" title="五、拓展"></a>五、拓展</h2><h3 id="全局异常处理"><a href="#全局异常处理" class="headerlink" title="全局异常处理"></a>全局异常处理</h3><p>声明式异常处理：将异常处理逻辑从具体业务逻辑中分离出来，通过配置方式进行统一管理和处理。</p>
<p>编程式异常处理：在代码显式编写异常处理代码。try..catch等</p>
<blockquote>
<p>基于注解声明异常处理</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//全局异常处理</span></span><br><span class="line"><span class="meta">@RestControllerAdvice</span> <span class="comment">//handler返回JSON字符串</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">GlobalExceptionHandle</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ExceptionHandler(ArithmeticException.class)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">ArithmeticException</span><span class="params">(ArithmeticException e)</span>&#123;</span><br><span class="line">        <span class="comment">//自定义异常处理</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> e.getMessage();</span><br><span class="line">        <span class="keyword">return</span> message;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 当上面的异常处理没有匹配，会走Exception异常处理</span></span><br><span class="line">    <span class="meta">@ExceptionHandler(Exception.class)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">ExceptionHandler</span><span class="params">(Exception e)</span>&#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> e.getMessage();</span><br><span class="line">        <span class="keyword">return</span> message;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h3><p><strong>拦截器（SpringMvc）比JavaWeb中Filter过滤器，更细</strong>。Filter只能在<strong>外部统一处理</strong>。</p>
<p><strong>拦截器则是在内部有更加细粒度的处理</strong>。</p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231030091815555.png" alt="image-20231030091815555"></p>
<blockquote>
<p>&#x3D;&#x3D;<strong>拦截器作用位置</strong>&#x3D;&#x3D;</p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231030092008587.png" alt="image-20231030092008587"></p>
</blockquote>
<blockquote>
<p><strong>多个拦截器的使用顺序</strong></p>
</blockquote>
<p>按照声明的顺序执行</p>
<h3 id="参数校验"><a href="#参数校验" class="headerlink" title="参数校验"></a>参数校验</h3><ul>
<li>@NotNull标注值不为空</li>
<li>@Min 最小值</li>
<li>@Size(max,min) 在max和min之间</li>
<li>@Pattern正则匹配</li>
<li>@NotEmpty 标注值字符串不能是空字符串</li>
<li>@Range 指定数字范围</li>
</ul>
<blockquote>
<p>易混总结</p>
</blockquote>
<ol>
<li>@NotNull(<strong>包装类型不为null</strong>)</li>
</ol>
<p>​		当字段值为null时，校验实现，<strong>不用用于字符串类型的校验</strong>。</p>
<ol start="2">
<li>@NotEmpty(<strong>集合类型不为空</strong>)</li>
</ol>
<p>​		对于Collection、map或数组对象属性进行校验，检查该属性是否为null或size()&#x3D;&#x3D;0，</p>
<p>​		需要注意：只校验空格前后的字符串。</p>
<ol start="3">
<li><p>@NotBlank（字符串不为null，且不为“”）</p>
<p><strong>对字符串类型进行校验</strong>，检查属性是否为null或“”或包含空格</p>
</li>
</ol>
<blockquote>
<p>导入依赖</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">           &lt;groupId&gt;org.hibernate.validator&lt;/groupId&gt;</span><br><span class="line">           &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;</span><br><span class="line">           &lt;version&gt;<span class="number">8.0</span><span class="number">.0</span>.Final&lt;/version&gt;</span><br><span class="line">       &lt;/dependency&gt;</span><br><span class="line">       &lt;dependency&gt;</span><br><span class="line">           &lt;groupId&gt;org.hibernate.validator&lt;/groupId&gt;</span><br><span class="line">           &lt;artifactId&gt;hibernate-validator-annotation-processor&lt;/artifactId&gt;</span><br><span class="line">           &lt;version&gt;<span class="number">8.0</span><span class="number">.0</span>.Final&lt;/version&gt;</span><br><span class="line">       &lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>步骤</p>
</blockquote>
<ol>
<li><strong>实体类</strong>添加<strong>校验注解</strong></li>
<li>方法上添加&#x3D;&#x3D;<strong>@Validated</strong>&#x3D;&#x3D;注解</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//BindingResult result绑定校验错误信息</span></span><br><span class="line">   <span class="meta">@RequestMapping(&quot;/hello&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">hello</span><span class="params">(<span class="meta">@RequestBody</span> <span class="meta">@Validated</span> User user, BindingResult result)</span>&#123;</span><br><span class="line">       <span class="keyword">if</span> (result.hasErrors())&#123;</span><br><span class="line">           <span class="comment">//如果发生错误，在这里处理</span></span><br><span class="line">           Map data=<span class="keyword">new</span> <span class="title class_">HashMap</span>();</span><br><span class="line">           data.put(<span class="string">&quot;code&quot;</span>,<span class="number">400</span>);</span><br><span class="line">           data.put(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;校验错误&quot;</span>);</span><br><span class="line">           <span class="keyword">return</span> data;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> user.toString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="六、跨域问题"><a href="#六、跨域问题" class="headerlink" title="六、跨域问题"></a>六、跨域问题</h2><ul>
<li><a target="_blank" rel="noopener" href="http://127.0.0.1:5173/">http://127.0.0.1:5173</a>   <a target="_blank" rel="noopener" href="http://localhost:8080/ssm">http://localhost:8080/ssm</a></li>
<li>浏览器认为是两个组织的资源，你不应该访问它。</li>
</ul>
<p>​		同源策略：<strong>比较访问方和被访问方的域名</strong></p>
<p>​		协议、IP、端口</p>
<p>解决：**@CrossOrgin**   &#x2F;&#x2F;允许其它源访问我们的Controller，<strong>浏览器就不拦截</strong></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/springmvc/" rel="tag"># springmvc</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2023/10/28/Mybatis/" rel="next" title="Mybatis">
                <i class="fa fa-chevron-left"></i> Mybatis
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2023/10/30/SpringBoot/" rel="prev" title="SpringBoot">
                SpringBoot <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#SpringMVC"><span class="nav-number">1.</span> <span class="nav-text">SpringMVC</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E7%AE%80%E4%BB%8B"><span class="nav-number">1.1.</span> <span class="nav-text">一、简介</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="nav-number">1.1.1.</span> <span class="nav-text">快速入门</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C%E3%80%81SpringMvc%E6%8E%A5%E6%94%B6%E6%95%B0%E6%8D%AE"><span class="nav-number">1.2.</span> <span class="nav-text">二、SpringMvc接收数据</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8E%A5%E6%94%B6%E5%8F%82%E6%95%B0"><span class="nav-number">1.2.1.</span> <span class="nav-text">接收参数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89%E3%80%81SpringMvc%E5%93%8D%E5%BA%94%E6%95%B0%E6%8D%AE"><span class="nav-number">1.3.</span> <span class="nav-text">三、SpringMvc响应数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B%E3%80%81RestFul%E9%A3%8E%E6%A0%BC"><span class="nav-number">1.4.</span> <span class="nav-text">四、RestFul风格</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9E%E6%88%98"><span class="nav-number">1.4.1.</span> <span class="nav-text">实战</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E6%8B%93%E5%B1%95"><span class="nav-number">1.5.</span> <span class="nav-text">五、拓展</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="nav-number">1.5.1.</span> <span class="nav-text">全局异常处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="nav-number">1.5.2.</span> <span class="nav-text">拦截器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E6%95%B0%E6%A0%A1%E9%AA%8C"><span class="nav-number">1.5.3.</span> <span class="nav-text">参数校验</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD%E3%80%81%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98"><span class="nav-number">1.6.</span> <span class="nav-text">六、跨域问题</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">黄宏涛</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
